const EventsEmitter = require('events');
//引入net模块
const net = require('net');
const {v4: uuidv4} = require('uuid');
const moment = require('moment');
const {hex2Bytes, bytes2HexStr, bytes2Str, str2Bytes} = require('../util/common-util');
const port = 18899;
const host = '114.217.55.239';
//创建TCP客户端
const client = new net.Socket();
//发布订阅事件对象
const event = new EventsEmitter();

const deviceCode = "C0132B69B154"
const version = "04"
const cmd = {"02": "下行-开始传数据", "03": "下行-心跳包", "04": "下行-发送二维码"}
let intervalId;

//设置连接的服务器
client.connect(port, host, function () {
    console.log("与服务端建立连接");
    event.emit("上行-发送设备ID", {client})
});

//监听data事件
client.on("data", function (data) {
    const res = data.toString('hex').toUpperCase();
    //打印数据
    const traceId = uuidv4().split("-")[4];
    // console.debug(`\n↓【${deviceCode}】【${traceId}】接收到原始数据为：${res}`);
    const bytes = hex2Bytes(res);
    for (let i = 0; i < bytes.length; i++) {
        i += 5;
        const funCode = bytes2HexStr(bytes.slice(i, i + 1));
        const length = parseInt(bytes2HexStr(bytes.slice(i + 1, i + 3)), 16);
        const content = bytes2HexStr(bytes.slice(i + 3, i + 3 + length))
        i += 2 + 3 + length;
        const funName = cmd[funCode];
        event.emit(funName, {funName, content, client, traceId})
    }
});

//监听end事件
client.on("end", function () {
    console.warn("socket end")
});

//监听error事件
client.on('error', function (e) {
    console.error('socket error', e);
});

// socket关闭的事件
client.on('close', function () {
    console.error('socket close');
    clearInterval(intervalId)
});

// -------事件处理--------
event.on("上行-发送设备ID", data => {
    const {client} = data;
    const deviceCodeBytes = str2Bytes(deviceCode);
    const lengthTemp = ("000" + deviceCodeBytes.length.toString(16));
    const length = lengthTemp.substring(lengthTemp.length - 4, lengthTemp.length)
    const content = bytes2HexStr(deviceCodeBytes);
    const str = `94C14EBA${version}01${length}${content}FFFFFF`;
    console.log(`\n↑【${deviceCode}】发送设备ID`, str)
    const buffer = Buffer.from(hex2Bytes(str));
    //给服务端发送数据
    client.write(buffer);
});

event.on("下行-开始传数据", (data) => {
    const {funName, client, traceId} = data;
    console.log(`↓【${funName}】【${deviceCode}】【${traceId}】`);
    const heartBeat = `94C14EBA${version}030000FFFFFF`;
    intervalId = setInterval(() => {
        const buffer = Buffer.from(hex2Bytes(heartBeat));
        client.write(buffer);
        console.log(`\n↑【${deviceCode}】【${traceId}】客户端发送心跳包`, moment().format('YYYY-MM-DD HH:mm:ss'))
    }, 5000);
});

event.on("下行-发送二维码", (data) => {
    const {funName, content, traceId} = data;
    const bytes = hex2Bytes(content);
    console.log(`↓【${funName}】【${deviceCode}】【${traceId}】二维码地址:`, bytes2Str(bytes));
});

event.on("下行-心跳包", (data) => {
    const {funName, content, traceId} = data;
    console.log(`↓【${funName}】【${deviceCode}】【${traceId}】客户端收到心跳包`, moment().format('YYYY-MM-DD HH:mm:ss'))
});
